package com.sms.web.domain.controller;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sms.core.request.SmsRequest;
import com.sms.domain.entity.Application;
import com.sms.domain.entity.Template;
import com.sms.domain.service.ApplicationService;
import com.sms.domain.service.TemplateService;
import com.sms.web.rest.RestObject;
import com.sms.web.utils.WebUtils;

/**
 * @desc 短信调试
 * @author wjw
 * @time 2017年11月16日下午4:25:47
 */
@Controller
@RequestMapping("/debug")
public class SmsController {
    
    protected static Logger logger = LoggerFactory.getLogger(SmsController.class);
    
    @Autowired
    private ApplicationService spplicationService;
    
    @Autowired
    private TemplateService templateService;
    
    @RequestMapping(value = "/sendtest")
    public String sendSmsTest() {
        return "sms/smstest";
    }
    
    @RequestMapping(value = "/send")
    @ResponseBody
    public RestObject send(SmsRequest ssr, HttpServletRequest request, HttpServletResponse response) {
        // 获取当前的请求路径
        String url = request.getRequestURL().substring(0, request.getRequestURL().lastIndexOf("/sms/send"));
        url += "/api/send";
        // 发送的请求参数
        Map<String, String> params = new HashMap<>();
        params.put("sign", "test");
        
        //获取请求参数
        Enumeration<String> keys = request.getParameterNames();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            params.put(key, StringUtils.trimToEmpty(request.getParameter(key)));
        }
        try {
			String resultBody = WebUtils.executePost(url, params);
			response.getWriter().print(resultBody);
			return null;
		} catch (Exception e) {
			logger.error("短信测试失败", e);
            return RestObject.newError("发送测试失败");
		}
    }
    
    @RequestMapping(value = "/application")
    @ResponseBody
    public RestObject getApplicationByUserId() {
    	Map<String, Object> filter = new HashMap<>();
        List<Application> data = spplicationService.findAll(filter);
        return RestObject.newOk(data);
    }
    
    @RequestMapping(value = "/template")
    @ResponseBody
    public RestObject getTemplateByUserId() {
    	Page<Template> page = templateService.findAll(1, 100);
        return RestObject.newOk(page.getContent());
    }
    
}
